<?php

namespace app\admin\model;

use think\Model;
use think\Exception;
use think\Db;
use think\Config;
use fast\Http;
use think\Log;

class YOnlineorder extends Model
{
    // 表名
    protected $name = 'y_onlineorder';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
    ];
    
    public function getStatusAttr($value)
    {
        switch ($value) {
            case '1':
                return '支付失败';
                break;
            case '2':
                return '支付成功';
                break;
            default:
                return '未支付';
                break;
        }
    }
    
    public function getPaymentAttr($value)
    {
        switch ($value) {
            case '0':
                return '支付宝';
                break;
            case '1':
                return '微信';
                break;
            case '3':
                return '苹果';
                break;
            default:
                return '-';
                break;
        }
    }
    
    public function getChannelAttr($value)
    {
        switch ($value) {
            case '1':
                return '代理';
                break;
            case '2':
                return '客户端';
                break;
            default:
                return '-';
                break;
        }
    }

    /**
     * 添加房卡 并 修改订单信息 并 添加推广员提成
     * @author violet
     * @since 2017-11-27
     */
    public function orderPay($orderID=0){
    
        $order_info = YOnlineorder::get(['orderID'=>$orderID,'status'=>0,'channel'=>2]);//订单详情
        $order_goods = YOrdergoods::get(['oid'=>$order_info['ID']]);//订单商品
        $order_log = YOrderlog::get(['oid'=>$order_info['ID']]);//订单记录
    
        //基础判断
        if(empty($order_info) || empty($order_goods) || empty($order_log)){
            throw new Exception('订单信息错误');
        }
        if($order_info->getData('status') == 1){
            throw new Exception('已经支付失败，请不要重复验证');
        }
        if($order_info->getData('status') == 2){
            throw new Exception('已经支付成功，请不要重复验证');
        }
        $goodsnum = ($order_goods['quotanum'] + $order_goods['givenum'])*$order_goods['goodsnum'];//商品总数
    
        //订单没有在游戏服务器上充值过时执行 游戏服务器 充值
        $recharge = Db::connect("GameDB")->table('recharge_record')->where(['orderid'=>$orderID])->find();//查询游戏服
        if(empty($recharge)){
            $sign = strtoupper(md5($order_info['uid'].$goodsnum.$order_info['orderID'].Config::get('Apikey.Gamekey')));//签名
            $sreq = [
                'uid' => $order_info['uid'],//玩家ID
                'diamond' => $goodsnum,//房卡数量
                'ordersid' => $order_info['orderID'],//订单编号
                'sign' => $sign,//签名参数
            ];
            //发送给游戏服务器
            if(Http::get(Config::get('GameDB.api_url').'recharge',$sreq) != 'ok')
            {
                Log::write('handleNotify-game:'.$order_info['orderID'].'服务器返回充值失败');
                throw new Exception('支付成功，充值失败');
            }
        }
    
        $bonustype = Config::get('Paykey.bonustype');
        //订单表、订单日志表、代理主表、推广提成表
        Db::startTrans();
        //订单 与 用户代理 关系表
        //判断 用户 是否存在代理关系 ，若存在则写入该表，不存在不写入
        if($bonustype == 1){
            $res = $this->userinvitationcodeAdd($order_info);
            if($res !== true){
                Db::rollback();
                throw new Exception($res['msg']);
            }
        }
        if($bonustype == 2){
            $res = $this->userinvitationcodeDlAdd($order_info);
            if($res !== true){
                Db::rollback();
                throw new Exception($res['msg']);
            }
        }
    
        //修改订单信息
        $order_info->status = 2;
        $order_info->updatetime = get_millisecond();
        $order_info->paytime = get_millisecond();
        if($order_info->save() == false){
            Db::rollback();
            throw new Exception('充值成功，订单信息修改失败');
        }
        $order_log->afnum = $order_log->bfnum + $goodsnum ;
        if($order_log->save() === false){
            Db::rollback();
            throw new Exception('充值成功，订单记录修改失败');
        }
        Db::commit();
    
        return true;
    }
    
    /**
     * 推广订单提成功能（后台配置提成比例）
     * @param $order_info
     */
    public function userinvitationcodeAdd($order_info){
    
        //判断该订单是否已经添加过提成数据，若没有则填写，若有则不填写直接跳出提成表
        if(Db::table('fa_y_promotionincome')->where(['orderID'=>$order_info['orderID']])->find()){
            $result['code'] = 1;
            $result['msg'] = '提成表已经填写过啦';
            return $result;
        }
        
        //邀请码
        $d_one = $d_two = $d_three = $d_four = $d_five = $result = $data = $list = [];
        $code = Db::table('fa_y_userinvitationcode')->where(['uid'=>$order_info['uid']])->find();
        if(empty($code)){
            return true;
        }
        //一级推广员
        $d_one = Db::table('fa_y_agency')->where(['code'=>$code['invitationCode']])->find();
        if(empty($d_one)){
            return true;
        }
        $tuid = $d_one['uid'];//直接代理ID
        //配比
        if($d_one['LevelID'] < 5){
            $level = $d_one['LevelID'];
        }else{
            $level = 5;
        }
        $bonus_config = Db::table('fa_y_bonus_config')->where(['level'=>$level])->find();
        if(empty($bonus_config)){
            return true;
        }
        
        $bonus_arr = array(
            '0' => $bonus_config['onegrade'],
            '1' => $bonus_config['twograde'],
            '2' => $bonus_config['threegrade'],
            '3' => $bonus_config['fourgrade'],
            '4' => $bonus_config['fivegrade'],
        );
        
        foreach ($bonus_arr as $key=>$val){
            if($tuid == 0){
                continue;
            }
            $t_agency = Db::table('fa_y_agency')->where(['uid'=>$tuid])->find();//代理信息

            $data[$key]['orderID'] = $order_info['orderID'];//订单编号
            $data[$key]['ordermount'] = $order_info['orderamount'];//订单金额
            $data[$key]['commission'] = $val;//提成比例
            $data[$key]['tuid'] = $t_agency['uid'];//提成玩家ID
            $data[$key]['money'] = ($order_info['orderamount'] * $val)/100;//提成金额
            $data[$key]['levelID'] = $key+1;//等级
            $data[$key]['addtime'] = get_millisecond();//提成时间
            
            if(Db::execute("UPDATE fa_y_agency set account=account+".(($order_info['orderamount'] * $val)/100)." WHERE `ID`=".$t_agency['ID']) === false){
                $result['code'] = 1;
                $result['msg'] = $key + 1 .'级写入提成失败';
                return $result;
            }
            
            $tuid = $t_agency['ParentID'];//上一次提成玩家ID
        }

        if(empty($data)){
            $result['code'] = 1;
            $result['msg'] = '写入提成数据丢失';
            return $result;
        }
        //操作提成表和账户余额
        $obj_yp = new YPromotionincome();
        if($obj_yp->saveAll($data) === false){
            $result['code'] = 1;
            $result['msg'] = '写入提成失败';
            return $result;
        }
        return true;
    }
    
    /**
     * 推广订单提成功能（代理配置提成比例）
     * @author violet
     * @since 2018-1-2
     */
    public function userinvitationcodeDlAdd($order_info){
        
        //判断该订单是否已经添加过提成数据，若没有则填写，若有则不填写直接跳出提成表
        if(Db::table('fa_y_promotionincome')->where(['orderID'=>$order_info['orderID']])->find()){
            $result['code'] = 1;
            $result['msg'] = '提成表已经填写过啦';
            return $result;
        }
        
        //邀请码
        $d_one = $d_two = $d_three = $result = $data = $list = [];
        $ParentID = $tgcommission = 0;
        $code = Db::table('fa_y_userinvitationcode')->where(['uid'=>$order_info['uid']])->value('invitationCode');
        if(empty($code)){
            return true;
        }
        $onethree = [0,1,2];
        foreach ($onethree as $i){
            if($i == 0){
                $d_one = Db::table('fa_y_agency')->where(['code'=>$code])->find();//直属 代理
            }elseif($ParentID != 0){
                $d_one = Db::table('fa_y_agency')->where(['uid'=>$ParentID])->find();//上级，上上级 代理
            }else{
                break;
            }
            if(empty($d_one)){
                break;
            }
            //存入提成表数据
            $data[$i]['orderID'] = $order_info['orderID'];//订单编号
            $data[$i]['ordermount'] = $order_info['orderamount'];//订单金额
            $data[$i]['tuid'] = $d_one['uid'];//提成玩家ID
            $data[$i]['levelID'] = $i+1;
            $data[$i]['addtime'] = get_millisecond();
            if($tgcommission == 0){
                $data[$i]['commission'] = $d_one['tgcommission'];//提成比例(百分比)
                $data[$i]['money'] = ($order_info['orderamount'] * $d_one['tgcommission'])/100;//提成金额
                $tgcommission = $d_one['tgcommission'];//提成比例(百分比)
            }else{
                $data[$i]['commission'] = $d_one['tgcommission'] - $tgcommission;//提成比例(百分比)
                $data[$i]['money'] = ($order_info['orderamount'] * ($d_one['tgcommission'] - $tgcommission))/100;//提成金额
                $tgcommission = $d_one['tgcommission'];//提成比例(百分比)
            }
            //修改 代理帐户余额
            if(Db::execute("UPDATE fa_y_agency set account=account+".$data[$i]['money']." WHERE `ID`=".$d_one['ID']) === false){
                $result['code'] = 1;
                $result['msg'] = '写入提成失败';
                return $result;
            }
            //上一级UID
            $ParentID = $d_one['ParentID'];
        }
    
        if(empty($data)){
            return true;
        }
        //操作提成表和账户余额
        $obj_yp = new YPromotionincome();
        if($obj_yp->saveAll($data) === false){
            $result['code'] = 1;
            $result['msg'] = '写入提成失败';
            return $result;
        }
        return true;
    }
    
    
}
